package com.dlc.shop.multishop.controller;

import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dlc.shop.allinpay.service.AllinpayCompanyService;
import com.dlc.shop.bean.enums.AuditStatus;
import com.dlc.shop.bean.model.ShopCompany;
import com.dlc.shop.bean.model.ShopDetail;
import com.dlc.shop.bean.vo.ShopCompanyVO;
import com.dlc.shop.common.Ocr.RecognizeBankCardOcr;
import com.dlc.shop.common.Ocr.RecognizeBusinessLicenseOcr;
import com.dlc.shop.common.Ocr.RecognizeIdcardOcr;
import com.dlc.shop.common.allinpay.constant.AllinpayConstant;
import com.dlc.shop.common.allinpay.constant.IdCardCollectProcessStatus;
import com.dlc.shop.common.allinpay.member.resp.CompanyInfo;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.common.util.ExceptionUtils;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.ShopCompanyService;
import com.dlc.shop.service.ShopDetailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author lth
 */

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/shop/shopCompany")
@Tag(name = "店铺工商信息接口")
public class ShopCompanyController {
    private final ShopCompanyService shopCompanyService;
    private final AllinpayCompanyService allinpayCompanyService;
    private final ShopDetailService shopDetailService;

    @PostMapping
    @Operation(summary = "新增店铺工商信息", description = "新增店铺工商信息")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:save')")
    public ServerResponseEntity<Void> save(@Valid @RequestBody ShopCompany shopCompany) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        checkAllinpay(shopCompany);
        shopCompany.setShopId(shopId);
        shopCompany.setStatus(AuditStatus.WAITAUDIT.value());
        shopCompanyService.saveInfo(shopCompany);
        return ServerResponseEntity.success();
    }

    private void checkAllinpay(ShopCompany shopCompany) {
        boolean needInfo = Objects.isNull(shopCompany.getLegalIds()) || Objects.isNull(shopCompany.getLegalPhone());
        if (allinpayCompanyService.getIsAllinpay() && needInfo) {
            throw new YamiShopBindException("开店所需要提交的信息有所变更，请重新填写");
        }
    }

    @PutMapping
    @Operation(summary = "更新店铺工商信息", description = "更新店铺工商信息")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:update')")
    public ServerResponseEntity<Void> update(@Valid @RequestBody ShopCompany shopCompany) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        checkAllinpay(shopCompany);
        shopCompany.setShopId(shopId);
        shopCompany.setStatus(AuditStatus.WAITAUDIT.value());
        shopCompanyService.updateByShopId(shopCompany);
        return ServerResponseEntity.success();
    }

    @PostMapping("/storage")
    @Operation(summary = "存储店铺工商信息", description = "存储店铺工商信息,已存在则更新，不存在则新增")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:save')")
    public ServerResponseEntity<Void> storage(@Valid @RequestBody ShopCompany shopCompany) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        checkAllinpay(shopCompany);
        shopCompany.setShopId(shopId);
        shopCompany.setStatus(AuditStatus.WAITAUDIT.value());
        if (shopCompanyService.count(Wrappers.lambdaQuery(ShopCompany.class).eq(ShopCompany::getShopId, shopId)) > 0) {
            shopCompanyService.updateByShopId(shopCompany);
        } else {
            shopCompanyService.saveInfo(shopCompany);
        }
        return ServerResponseEntity.success();
    }

    @GetMapping
    @Operation(summary = "获取店铺工商信息", description = "获取店铺工商信息")
    @Parameter(name = "status", description = "审核状态：1：已通过 0待审核 -1未通过")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:info')")
    public ServerResponseEntity<ShopCompanyVO> getShopCompanyByShopId(@RequestParam(value = "status", required = false, defaultValue = "1") Integer status) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (allinpayCompanyService.getIsAllinpay()) {
            // 影印件还没通过审核
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
            if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                status = AuditStatus.WAITAUDIT.value();
            }
        }
        ShopCompanyVO shopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, status);
        if (Objects.nonNull(shopCompany) && Objects.nonNull(shopCompany.getLegalPhone())) {
            shopCompany.setLegalPhone(PhoneUtil.hideBetween(shopCompany.getLegalPhone()).toString());
        }
        return ServerResponseEntity.success(shopCompany);
    }

    @PutMapping("/updateIdCardStatus")
    @Operation(summary = "更新影印件状态", description = "通联独有")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:update')")
    public ServerResponseEntity<Integer> updateIdCardStatus() {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!allinpayCompanyService.getIsAllinpay()) {
            return ServerResponseEntity.success();
        }
        ShopCompanyVO shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        if (Objects.isNull(shopCompanyVO)) {
            shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.SUCCESSAUDIT.value());
        }
        ShopDetail shopDetailVO = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
            // 更新下更新时间
            shopCompanyService.updateById(BeanUtil.map(shopCompanyVO, ShopCompany.class));
            // 已经审核通过不用更新
            return ServerResponseEntity.success(shopDetailVO.getIdCardCollectProcessStatus());
        }
        // 可能回调有问题导致这里没刷新，所以多给一个接口
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(AllinpayConstant.SHOP + shopId);
        Integer status = allinpayCompanyService.getIdCardStatus(companyInfo.getOcrRegnumComparisonResult(), companyInfo.getOcrIdcardComparisonResult());
        if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), status)) {
            // 更新下更新时间
            shopCompanyService.updateById(BeanUtil.map(shopCompanyVO, ShopCompany.class));
            // 状态一致不用更新
            return ServerResponseEntity.success(status);
        }
        shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, status);
        shopDetailService.removeShopDetailCacheByShopId(shopId);
        return ServerResponseEntity.success(status);
    }

    @PutMapping("/uploadIdCard")
    @Operation(summary = "重新上传影印件", description = "通联独有")
    @PreAuthorize("@pms.hasPermission('shop:shopCompany:update')")
    public ServerResponseEntity<String> uploadIdCard(@RequestBody ShopCompany shopCompanyDTO) {
        if (!allinpayCompanyService.getIsAllinpay()) {
            return ServerResponseEntity.success("非通联环境");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        shopCompanyDTO.setShopId(shopId);
        if (Objects.isNull(shopId)) {
            throw new YamiShopBindException("店铺id不能为空");
        }
        ShopDetail shopDetailVO = shopDetailService.getShopDetailByShopId(shopId);
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(AllinpayConstant.SHOP + shopId);
        Integer status = allinpayCompanyService.getIdCardStatus(companyInfo.getOcrRegnumComparisonResult(), companyInfo.getOcrIdcardComparisonResult());
        String result = shopCompanyService.uploadIdCard(shopCompanyDTO, shopDetailVO, status);
        shopDetailService.removeShopDetailCacheByShopId(shopId);
        if (!Objects.equals(result, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS) || Objects.equals(result, AllinpayConstant.ID_CARD_UPDATE_SUCCESS)) {
            return ServerResponseEntity.showFailMsg(result);
        }
        return ServerResponseEntity.success(result);
    }



}
